﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HtmlAgilityPack;
using HtmlPictureHelper.Enums;
using HtmlPictureHelper.Interface;
using HtmlPictureHelper.Analyzer;
using HtmlPictureHelper.Model;
namespace HtmlPictureHelper
{
    public partial class MainForm : Form
    {

        public MainForm()
        {
            InitializeComponent();
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnAnalysis_Click(object sender, EventArgs e)
        {
            btnClear_Click(sender, e);
            string webPageUrl = this.txtWebPageUrl.Text;

            PictureAnalyzer pictureAnalyzer = new PictureAnalyzer(webPageUrl);

            AnalyzedPictureModel model = pictureAnalyzer.GetAnalyzedPictureModel();

            Uri uri = new Uri(webPageUrl);
            if (string.IsNullOrEmpty(webPageUrl))
            {
                MessageBox.Show("地址不能为空", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if(model !=null)
            {
                this.toolStripStatusLabel1.Text=$"{model.PictureCaption} ({ model.PictureLinks.Count})";
                this.listAnalyzedList.Tag = model;
                foreach (var item in model.PictureLinks)
                {
                    this.listAnalyzedList.Items.Add($"{item.OriginalString}");
                }
            }
            else
            {
                this.toolStripStatusLabel1.ForeColor = Color.Red;
                this.toolStripStatusLabel1.Text="页面地址异常，分析失败";

            }
            
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.listAnalyzedList.Items.Clear();
            this.pBoxPreview.Image = null;
            this.toolStripStatusLabel1.Text = "";
            this.toolStripStatusLabel1.ForeColor = Color.Black;
            this.toolStripStatusLabel2.Text = "";
            this.toolStripProgressBar1.Value = 0;
        }

        private void listAnalyzedList_DoubleClick(object sender, EventArgs e)
        {
            if(this.listAnalyzedList.SelectedItem == null)
            {
                return;
            }
            string pictureUri = this.listAnalyzedList.SelectedItem as string;
            pBoxPreview.Load(pictureUri);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            string pictureLink = (string)this.listAnalyzedList.SelectedItem;
            if (string.IsNullOrEmpty(pictureLink))
            {
                MessageBox.Show("未选中任何图片", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if(fbd.ShowDialog() == DialogResult.OK)
            {
                string saveFileName = Path.Combine(fbd.SelectedPath, Path.GetFileName(pictureLink));
                Utility.WebDownloadUtility.DownloadSinglePicture((string)this.listAnalyzedList.SelectedItem,saveFileName,(s,arg)=> {
                    this.toolStripStatusLabel1.Text = $"{pictureLink} 下载完成";
                },(s,arg)=> {
                    this.toolStripProgressBar1.Value = arg.ProgressPercentage;
                    this.toolStripStatusLabel2.Text = $"{arg.BytesReceived/1000f} kb / {arg.TotalBytesToReceive/1000f} kb";
                });
            }
        }

        private void btnSaveAll_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            string pictureLink = (string)this.listAnalyzedList.SelectedItem;
            Model.AnalyzedPictureModel model = this.listAnalyzedList.Tag as Model.AnalyzedPictureModel;
            if (this.listAnalyzedList.Items.Count == 0)
            {
                MessageBox.Show("列表中无任何图片", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            if (model == null || string.IsNullOrEmpty(model.PictureCaption) || model.PictureLinks==null || model.PictureLinks.Count <=0)
            {
                MessageBox.Show("网页数据异常", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (fbd.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            //图片保存目录名处理
            string savePath  = Path.Combine(fbd.SelectedPath, model.PictureCaption);
            if (Directory.Exists(savePath))
            {
                DialogResult result = MessageBox.Show($"保存目录 {savePath} 已存在，是否覆盖此文件夹下的所有文件？","系统提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
                if(result == DialogResult.OK)
                {
                    Directory.Delete(savePath,true);
                }
                else
                {
                    return;
                }
            }
            //创建以图片标题命名的新文件夹
            Directory.CreateDirectory(savePath);
            


            Utility.WebDownloadUtility.DownloadAnalyzedPicture(model, savePath,(arg)=> {
                string message = $"{arg.PictureCount}张图片下载完成，共计{arg.TotalBytesCount/ 1024} kb,用时{arg.TotalMilliseconds / 1000} 秒";
                MessageBox.Show(message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return 0;
            },(s,arg)=>
            {
                Console.WriteLine(arg.UserState);
                this.toolStripProgressBar1.Value = arg.ProgressPercentage;
                this.toolStripStatusLabel2.Text = $"{arg.ProgressPercentage}%";
            });

        }

        private void 退出XToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void 选项OToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SettingForm settingForm = new SettingForm();
            settingForm.ShowDialog();

        }

        private void 关于AToolStripMenuItem_Click(object sender, EventArgs e)
        {
            new AboutForm().ShowDialog();
        }
    }
}
